package cn.tedu.v2_3;

import java.io.*;
import java.net.ConnectException;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.Scanner;

/**
 * Version2.3  多人聊天室
 *     持续优化：关闭通讯、代码简洁
 *     练习：1.Client 添加ip 功能
 *          2.Server 关闭通讯、代码简洁优化，写Client 关闭通讯、代码简洁优化
 * Version3.0 升级 双向链接【客户端与服务器相互说话】
 */
public class Client {
    private Socket socket;
    public Client() {
        try {
            socket=new Socket("172.20.10.2",3545);
        } catch (NullPointerException e){
            System.out.println("IP传入错误导致链接失败");
        } catch (UnknownHostException e){
            System.out.println("IP传入出错");
        } catch (ConnectException e){
            System.out.println("客户端链接失败：建议检查IP或者端口号");
        } catch (IOException e) {
            System.out.println("客户端链接服务器失败，提示：检查IP/端口");
        }
    }
    public void start(){
        PrintWriter pw=null;
        try {
            pw=new PrintWriter(new BufferedWriter(new OutputStreamWriter(socket.getOutputStream(),"UTF8")),true);
            System.out.println("对服务器端说话：");
            Scanner input=new Scanner(System.in);
            String line=null;
            while(true){
                line=input.nextLine();
                pw.println(line);
                System.out.println("写出成功");
            }
        } catch (UnsupportedEncodingException e) {
            System.out.println("客户端/服务器端编码集有问题");
        } catch (IOException e){
            System.out.println("客户端链接服务器端：IO流操作出现问题");
        } finally {
            if (socket != null&& socket.isClosed())
                try {
                    socket.close();
                } catch (IOException e) {
                    System.out.println("通讯关闭失败");
                }
        }if (pw!=null)
                pw.close();
    }
    public static void main(String[] args) throws IOException {
        new Client().start();
    }
}

